package com.teacher.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.mapper.NoticeMapper;
import com.teacher.pojo.dto.notice.NoticeAddDto;
import com.teacher.pojo.dto.notice.NoticeDto;
import com.teacher.pojo.dto.notice.NoticeUpdateDto;
import com.teacher.pojo.dto.notice.NoticeAddDto;
import com.teacher.pojo.dto.notice.NoticeDto;
import com.teacher.pojo.dto.notice.NoticeUpdateDto;
import com.teacher.pojo.entity.Notice;
import com.teacher.pojo.entity.Notice;
import com.teacher.mapper.NoticeMapper;
import com.teacher.pojo.entity.WechatUser;
import com.teacher.pojo.vo.notice.NoticeVo;
import com.teacher.pojo.vo.notice.NoticeVo;
import com.teacher.service.INoticeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 公告 服务实现类
 * </p>
 *
 * @author jiangzhuohang
 * @since 2024-03-14
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private HttpServletRequest httpServletRequest;



    @Override
    public IPage<NoticeVo> getNoticePageData(NoticeDto pageVo) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        System.out.println(userDetails.getUsername());
        Page page = new Page(pageVo.getCurrentPage(), pageVo.getPageSize());
        IPage<NoticeVo> noticePageData = noticeMapper.getNoticePageData(page, pageVo);
        return noticePageData;
    }

    @Override
    public CommonResult addNotice(NoticeAddDto dto) {
        Notice notice = new Notice();
        BeanUtil.copyProperties(dto,notice);
        int insert = noticeMapper.insert(notice);
        if (insert<1) {
            return CommonResult.failed("新增失败");
        }
        return CommonResult.success("通知成功");
    }

    @Override
    public CommonResult deleteNotice(List<Long> list) {
        int i = noticeMapper.deleteBatchIds(list);
        if (i<1){
            return CommonResult.failed("删除失败");
        }
        return CommonResult.success("删除成功");
    }

    @Override
    public CommonResult updateNotice(NoticeUpdateDto updateDto) {
        Notice notice = new Notice();
        BeanUtil.copyProperties(updateDto,notice);
        int i = noticeMapper.updateById(notice);
        if (i<1){
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("更新成功");
    }

    @Override
    public CommonResult getSysNotice() {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        List<Notice> notices = noticeMapper.selectList(new QueryWrapper<Notice>().lambda().eq(Notice::getAcceptOpenId, openid)
        .eq(Notice::getIsRead,0));

        return CommonResult.success(notices);
    }

    @Async
    //异步推送申请拼车消息
    public void sendCarpoolMessage(String openId,Long relevanceId,String name,String content){
        System.out.println("异步方法推送订阅消息开始: " + Thread.currentThread().getName());

        //获取AccessToken
        String appId = "wxb4632b40969646bb";
        String appSecret = "8806f39cc7880a535c8b9522f9fc8d4c";
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
        String accessToken = JSONUtil.parseObj(result).getStr("access_token");

        //装载消息体
        JSONObject body=new JSONObject();
        body.put("touser",openId);
        body.put("miniprogram_state","trial");
        body.put("lang","zh_CN");
        body.put("page","/pages/map/map?id="+relevanceId+"&type=1");
        //模板id
        body.put("template_id","V7VvZF52YvIRfAXOlkLrX3bITdopGBc1JS2y9yXpGVY");
        JSONObject json=new JSONObject();
        json.put("name2",new JSONObject().put("value",name));
        json.put("date3",new JSONObject().put("value", DateUtil.now().toString()));
        json.put("thing4",new JSONObject().put("value",content));
        body.put("data",json);
        //发送
        String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());

        System.out.println("异步方法推送订阅消息结束: " + Thread.currentThread().getName());
        System.out.println("推送结果: " + post);

    }

    @Override
    public CommonResult readNotice(Long noticeId) {
        LambdaUpdateWrapper<Notice> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Notice::getIsRead,1);
        updateWrapper.eq(Notice::getId,noticeId);
        int update = noticeMapper.update(null, updateWrapper);
        if (update<1){
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("已读成功");
    }

    @Async
    //异步推送拼车结果消息
    public void sendCarpoolRespondMessage(String openId,Long relevanceId,String carpoolResult,String name){
        System.out.println("异步方法推送订阅消息开始: " + Thread.currentThread().getName());

        //获取AccessToken
        String appId = "wxb4632b40969646bb";
        String appSecret = "8806f39cc7880a535c8b9522f9fc8d4c";
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
        String accessToken = JSONUtil.parseObj(result).getStr("access_token");

        //装载消息体
        JSONObject body=new JSONObject();
        body.put("touser",openId);
        body.put("miniprogram_state","trial");
        body.put("lang","zh_CN");
        body.put("page","/pages/map/map?id="+relevanceId+"&type=1");
        //模板id
        body.put("template_id","U3KQbnwTekAsn5FQWzi8tftgKr8Q3V7Pvu6Lwn6Gq_w");
        JSONObject json=new JSONObject();
        json.put("thing3",new JSONObject().put("value",name));
        json.put("thing1",new JSONObject().put("value", "你申请的同乘有一条新的审核结果"));
        json.put("thing2",new JSONObject().put("value",carpoolResult));
        body.put("data",json);
        //发送
        String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());

        System.out.println("异步方法推送订阅消息结束: " + Thread.currentThread().getName());
        System.out.println("推送结果: " + post);

    }

    @Async
    //异步推送拼车评价消息
    public void sendCarpoolCommentMessage(String openId,Long relevanceId,String comment,Float score){
        System.out.println("异步方法推送订阅消息开始: " + Thread.currentThread().getName());


        //获取AccessToken
        String appId = "wxb4632b40969646bb";
        String appSecret = "8806f39cc7880a535c8b9522f9fc8d4c";
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
        String accessToken = JSONUtil.parseObj(result).getStr("access_token");

        //装载消息体
        JSONObject body=new JSONObject();
        body.put("touser",openId);
        body.put("miniprogram_state","trial");
        body.put("lang","zh_CN");
        body.put("page","/pages/map/map?id="+relevanceId+"&type=1");
        //模板id
        body.put("template_id","S6VfJhv9HCr1-I2RodSg_6WGkUZql4aWgB8ix8XbWxg");
        JSONObject json=new JSONObject();
        json.put("phrase1",new JSONObject().put("value",comment));
        json.put("number5",new JSONObject().put("value", score));
        json.put("date3",new JSONObject().put("value",DateUtil.now().toString()));
        body.put("data",json);
        //发送
        String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());

        System.out.println("异步方法推送订阅消息结束: " + Thread.currentThread().getName());
        System.out.println("推送结果: " + post);

    }
}
